<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
    </head>
    <body></body>
    <script type="module">
        import { Application, Graphics } from "https://cdn.skypack.dev/pixi.js";
        const app = new Application({
            antialias: true, // default: false 反锯齿
            transparent: false, // default: false 透明度
            resolution: 1, // default: 1 分辨率
        });
        document.body.appendChild(app.view);
        window.app = app;
        function createSprite(x = 0, y = 0, color = 0xffffff, scale = 1) {
            let rect = new Graphics();
            rect.beginFill(color);
            rect.drawRect(0, 0, 10 * scale, 10 * scale);
            rect.endFill();
            rect.position.set(x, y);
            app.stage.addChild(rect);
            return rect;
        }
        function changeColor(rect, color, scale = 1) {
            rect.beginFill(color);
            rect.drawRect(0, 0, 10 * scale, 10 * scale);
            rect.endFill();
        }

        import { Flock, Vector, Emitter } from "../dist/index.js";
        // 生成鸟群
        const flock = new Flock();
        const sprites = [...Array(20).keys()].map((i) => {
            flock.addRandomBoid(new Vector(20, 20));
            return createSprite();
        });

        // 生成信息素
        const food = new Emitter(
            () => new Vector(400, 400),
            4000,
            200,
            "log",
            false
        );
        flock.addEmitter(food);
        const foodBody = createSprite(400, 400, 0xff0000, 2);

        // 让信息素跟随鼠标
        app.view.addEventListener("mousemove", ({ offsetX: x, offsetY: y }) => {
            if (Math.random() > 0.7) {
                food.moveTo(x, y);
                foodBody.position.set(x, y);
            }
        });
        app.view.addEventListener("click", () => {
            food.repel = !food.repel;
            console.log(food.repel);
            changeColor(foodBody, food.repel ? 0x0000ff : 0xff0000, 2);
        });
        window.food = food;
        console.log(sprites);

        // 添加每帧循环
        app.ticker.add(() => {
            flock.update();
            flock.flock.forEach((i, index) => {
                const { x, y } = i.position;
                const rect = sprites[index];
                rect.position.set(x, y);

                // 展示鸟的不同的属性
                let color = 0x0000ff;
                switch (i.majorInfluence) {
                    case "cohesion":
                        color = 0xff0000;
                        break;

                    case "claustrophobia":
                        color = 0x00ff00;
                        break;
                }
                changeColor(rect, color);
            });
        });
    </script>
</html>
